import React, { useState, useRef, useEffect } from "react";
import "../assets/css/shouyeshouqi.css";
import { DownOutlined, UpOutlined } from "@ant-design/icons";
import { Pagination, Checkbox } from "antd";
import im from "../assets/images/形状.png";
import bian from "../assets/images/编辑按钮.png";
import Kehuhguanliyou from "./Kehuguanliyou";
import NewCustomerModal from "./NewCustomerModal";
import axios from "axios";

export default function Shouyeshouqi() {
  const [zhankaishouqi, genxinzhi] = useState(false);
  const [isMaskVisible, setIsMaskVisible] = useState(false);
  const [isBatchImportVisible, setIsBatchImportVisible] = useState(false);
  const [isClicked, setIsClicked] = useState(false);
  const [selectedItem, setSelectedItem] = useState(null);
  const [currentTab, setCurrentTab] = useState("客户详情"); // 默认显示客户详情 Tab
  const contentRef = useRef(null);
  const [currentPage, setCurrentPage] = useState(1);
  const pageSize = 10;
  const [dataSource, setDataSource] = useState([]); // 数据存储
  const [currentIndex, setCurrentIndex] = useState(null); // 当前选中索引
  const [isDetailVisible, setIsDetailVisible] = useState(false); // 控制右侧弹出
  const renderRange = [0, 10]; // 控制渲染范围的索引（0 到 10）
  const [leaseData, setLeaseData] = useState([]); // 用于存储租期数据

  useEffect(() => {
    // 获取租期数据
    axios
      .get("http://172.16.17.120:8080/getxinjian")
      .then((response) => {
        setLeaseData(response.data); // 更新租期数据
      })
      .catch((error) => {
        console.error("获取租期数据失败", error);
      });
  }, []);

  const toggleMask = () => {
    setIsMaskVisible(!isMaskVisible);
  };

  const handleTabChange = (tab) => {
    setCurrentTab(tab); // 更新当前 Tab
  };
  const toggleStyle = () => {
    setIsClicked(!isClicked);
  };

  const showDetails = (index) => {
    setCurrentIndex(index); // 设置选中索引
    setIsDetailVisible(true); // 显示右侧弹出组件
  };

  useEffect(() => {
    // 初始加载数据
    getData();

    // 每隔 5 秒获取一次最新数据
    const intervalId = setInterval(() => {
      getData();
    }, 2000);

    // 在组件卸载时清除定时器
    return () => clearInterval(intervalId);
  }, [currentPage]); // 监听当前页变化

  // 隐藏详情
  const hideDetails = () => {
    setIsDetailVisible(false); // 隐藏右侧弹出组件
    setCurrentIndex(null); // 清空选中索引
  };
  const toggleBatchImport = () => {
    setIsBatchImportVisible(!isBatchImportVisible);
  };

  const handleUpdate = async (updatedData) => {
    try {
      // 调用后端 API 更新数据
      await axios.put("http://172.16.17.120:8080/xinjianxiu", updatedData);

      // 更新前端数据
      const updatedDataSource = dataSource.map((item, index) =>
        index === currentIndex ? updatedData : item
      );
      setDataSource(updatedDataSource);
      alert("更新成功！");
    } catch (error) {
      console.error("更新失败：", error);
      alert("更新失败，请稍后重试！");
    }
  };

  const handleDelete = async (index) => {
    const itemToDelete = dataSource[index];
    const id = itemToDelete.id;

    try {
      // 调用后端 API 删除记录
      await axios.delete("http://172.16.17.120:8080/xinjianshan", {
        data: { id },
      });

      // 更新前端数据源
      const updatedData = dataSource.filter((_, i) => i !== index);
      setDataSource(updatedData);
      setIsDetailVisible(false); // 关闭详情面板
      alert("删除成功！");
    } catch (error) {
      console.error("删除失败：", error);
      alert("删除失败，请稍后重试！");
    }
  };

  const getData = () => {
    axios
      .get("http://172.16.17.120:8080/getxinjian", {
        params: {
          act: "index",
          op: "getHomeMoreProduct",
          curpage: currentPage,
          xxclient: "new",
        },
      })
      .then((res) => {
        setDataSource(res.data || []); // 更新数据
      })
      .catch((err) => {
        console.error("获取数据失败：", err);
      });
  };
  // 在组件挂载时获取数据
  useEffect(() => {
    getData(1); // 默认获取第一页数据
  }, []);
  const [filters, setFilters] = useState({
    notStarted: false,
    ongoing: false,
    ended: false,
  });
  const data = [
    {
      name: "北京西天取经科技有限公司",
      notStarted: "-",
      ongoing: "是",
      ended: "-",
      maxArea: "是",
      daysStayed: 80,
      daysLeft: 30,
    },
    // 更多数据可以添加在这里
  ];

  const paginatedData = data.slice(
    (currentPage - 1) * pageSize,
    currentPage * pageSize
  );
  const handleFilterChange = (checkedValues, filterKey) => {
    setFilters({ ...filters, [filterKey]: checkedValues });
  };

  const handlePageChange = (page) => {
    setCurrentPage(page); // 更新当前页
    getData(); // 获取新页数据
  };

  const handleIndexChange = (e) => {
    setCurrentIndex(Number(e.target.value));
  };

  useEffect(() => {
    getData();
  }, []);

  const shouzhan = () => {
    genxinzhi(!zhankaishouqi);
  };

  useEffect(() => {
    if (contentRef.current) {
      contentRef.current.style.height = zhankaishouqi
        ? "0px"
        : `${contentRef.current.scrollHeight}px`;
    }
  }, [zhankaishouqi]);


  return (
    <div className="zkehuguanshou">
      <div className="zshouzhoz">
        <input
          className="zshouzhosou"
          type="text"
          placeholder="请输入客户名称"
        />
        <div className="zshouzho">
          <div
            ref={contentRef}
            style={{
              height: "0px",
              overflow: "hidden",
              transition: "1s",
            }}
          >
            <div>
              <div className="zshouzhoyinyi">
                <div className="zshouzhoyinyiyyy">短期状态</div>
                <Checkbox className="zshouzhoyinyixuan">有未开始的租期</Checkbox>
                <Checkbox className="zshouzhoyinyixuan">租期进行中</Checkbox>
                <Checkbox className="zshouzhoyinyixuan">有已结束的租期</Checkbox>
              </div>
              <div className="zshouzhoyiner">
                <div className="zshouzhoyinyiyyi">联系人姓名或手机号</div>
                <input className="zshouzhoyinyisousuio" type="text" />
              </div>
            </div>
          </div>
          <div className="zshoudong">
            <div className="zshouzhoshou"></div>
            <div className="zshouzhozi" onClick={shouzhan}>
              {zhankaishouqi ? (
                <div>
                  <DownOutlined />
                  <span>更多筛选</span>
                </div>
              ) : (
                <div>
                  <UpOutlined />
                  <span>收起筛选</span>
                </div>
              )}
            </div>
          </div>
        </div>
        <div className="zshouzhoxia">
          <div className="zshouzhoxiazuo">查询</div>
          <div className="zshouzhoxiayou">重置</div>
        </div>
      </div>
      <div className="zshouxiaz">
      <div className="zshouxiatouuu">
          <div className="zshouxiatouy">客户名称</div>
          <div className="zshouxiatouer">有未开始的租期</div>
          <div className="zshouxiatouer">租期进行中</div>
          <div className="zshouxiatouer">有已结束的租期</div>
          <div className="zshouxiatouer">联系人</div>
          <div className="zshouxiatouer">联系人手机号</div>
          <div className="zshouxiatouer">联系人邮箱</div>
          <div className="zshouxiatouer">联系人职务</div>
          <div className="zshouxiatouer">操作</div>
        </div>

        {dataSource.length > 0 ? (
          dataSource.map(
            (item, index) =>
              index >= renderRange[0] &&
              index < renderRange[1] && ( // 限制渲染范围
                <div
                  className="zshouxiatouooo"
                  key={index}
                  onClick={() => showDetails(index)} // 点击事件绑定
                  style={{ cursor: "pointer" }}
                >
                  <div className="zshouxiatouyy">{item?.kename || "-"}</div>
                  <div className="zshouxiatoueer">{item?.keuser || "-"}</div>
                  <div className="zshouxiatouersan">{item?.ongoing || "-"}</div>
                  <div className="zshouxiatouersi">{item?.ended || "-"}</div>
                </div>
              )
          )
        ) : (
          <div>未找到数据...</div>
        )}
     <Pagination
  className="zshoupagination"
  current={currentPage}
  pageSize={pageSize}
  total={Array.isArray(dataSource) ? dataSource.length : 0}
  onChange={handlePageChange}
/>

      </div>
    </div>
  );
}
